<template>
  <div class="container">
    <div class="header">
      <div class="left-header">
        <select v-model="selectedGroup" @change="fetchImages">
          <option v-for="group in groups" :key="group.id" :value="group.id">
            {{ group.name }}
          </option>
        </select>
      </div>
      <div class="header-right">
        <div class="date-filter">
          <input type="date" v-model="startDate" class="inputselect"/>
          <span>至</span>
          <input type="date" v-model="endDate"  class="inputselect"/>
          <button @click="applyDateFilter" class="buttonselect">筛选</button>
        </div>
        <div class="batch-actions">
          <button @click="selectAll" class="buttonselect">全选</button>
          <button @click="deselectAll" class="buttonselect">全不选</button>
          <button @click="deleteSelected" :disabled="selectedImages.length === 0" class="buttonselect">删除选中</button>
          <button @click="exportImages" :disabled="selectedImages.length === 0" class="buttonselect">导出图片</button>
        </div>
        <button class="img-upload" @click="openUploadModal">图片上传</button>
      </div>
    </div>
    <hr style="FILTER: alpha(opacity=100,finishopacity=0,style=3)" width="80%" color=#e4e4e4 SIZE=1>
  
    <div class="image-grid-container">
      <div class="image-grid">
        <div class="image-card" v-for="image in paginatedImages" :key="image.id" @click="openModal(image)">
          <input
            type="checkbox"
            v-model="selectedImages"
            :value="image.id"
            class="image-checkbox"
            @click.stop
          />
          <img :src="image.imageUrl" :alt="image.cameraName" />
          <div class="image-info">
            <p>{{ image.cameraName }}</p>
            <p>{{ formatDate(image.createTime) }}</p>
          </div>
        </div>
      </div>
    </div>

    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>

    <div v-if="showModal" class="modal-overlay" @click.self="closeModal">
      <div class="modal-content">
        <div class="modal-header">
          <span class="image-time">{{ formatDate(selectedImage.createTime) }}</span>
          <button class="close-button" @click="closeModal">&times;</button>
        </div>
        <div class="model-content">
          <img class="image" :src="selectedImage.imageUrl" :alt="selectedImage.cameraName" />
          <div class="modal-sidebar">
            <h3>功能按钮</h3>
            <button class="modal-button" @click="handleHatRecognition">安全帽检测</button>
            <button class="modal-button" @click="handleFireRecognition" >火焰检测</button>
            <button class="modal-button" @click="handleSmokeRecognition" >烟雾检测</button>
            <!-- 样式能展示空行 -->
            <div style="white-space: pre-line;">
              {{ result }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图片上传弹窗 -->
    <div v-if="showUploadModal" class="modal-overlay" @click="closeUploadModal"></div>
    <div
      v-if="showUploadModal"
      class="upload-modal">
      <div class="upload-modal-content">
        <div class="title">
          <h3>图片上传</h3>
        </div>
        <div class="form-item">
          <label for="device">选择设备：</label>
          <select v-model="uploadData.selectedDevice" id="device">
            <option v-for="group in groups" :key="group.id" :value="group.id">
              {{ group.name }}
            </option>
          </select>
        </div>
        <div class="form-item">
          <label for="time">选择时间：</label>
          <input type="datetime-local" v-model="uploadData.selectedTime" id="time" />
        </div>
        <div class="form-item">
          <label for="image">选择图片：</label>
          <input type="file" @change="handleFileUpload" id="image" />
        </div>
        <div class="form-actions">
          <button @click="uploadImage" class="buttonsave">保存</button>
          <button @click="closeUploadModal" class="buttoncancel">取消</button>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { getPhotoOperationPict } from "@/api/file";
import { hatRecognition } from "@/api/image";
import useOperationStore from '../../../../../store/operation';
import {reqOperationDevice} from '@/api/device'

// 获取并监听 operationStore 的变化
let operationStore = useOperationStore();
let operationId = ref(operationStore.data.length > 0 ? operationStore.data[operationStore.index].id : '');
// 当 operationStore 数据变化时，更新 operationId
operationStore.$subscribe(async (mutation, state) => {
    operationId.value = operationStore.data[operationStore.index].id;
    await fetchdeviceData(); // 重新获取监测数据
});

const deviceData = ref([])

const fetchdeviceData = async () => {
  if (!operationId.value) return;
  const response = await reqOperationDevice(operationId.value);
  if (response.code === 0) {
    deviceData.value = response.data;
    groups.value = deviceData.value.map((device) => ({
      id: device.id,
      name: device.name,
    }));

    // 自动选择第一个分组并刷新图片
    if (groups.value.length) {
      const newGroupId = groups.value[0].id;
      if (selectedGroup.value !== newGroupId) {
        selectedGroup.value = newGroupId;
        await fetchImages(); // 刷新图片列表
      }
    }
  } else {
    console.error('获取设备数据失败');
  }
};



const groups = ref([]);
const selectedGroup = ref(null);
const images = ref([]);
const filteredImages = ref([]);
const selectedImages = ref([]);
const currentPage = ref(1);
const itemsPerPage = 12; // 每页显示 12 张图片

const startDate = ref("");
const endDate = ref("");

const result = ref("点击功能按钮进行检测");

const showUploadModal = ref(false);
const uploadData = ref({
  selectedDevice: null,
  selectedTime: "",
  selectedImage: null,
});

const handleHatRecognition = async () => {
    result.value = "安全帽检测中...";
    let formData = new FormData();
    formData.append("imageUrl", selectedImage.value.imageUrl);
    const response = await hatRecognition(formData);
    const data = response.data.data
    if (response.code == 0) {
      console.log(data);
      
      let num = data.length
      result.value = `检测成功，共检测到${num}个目标\n`;
      for(let i = 0; i < num; i++) {
        let item = data[i]
        if(item.type == 'no_hat') {
          result.value += `未佩戴安全帽位置：` + item.leftTopX + "," + item.leftTopY + " " + item.rightBottomX + "," + item.rightBottomY + "\n";
        } else {
          result.value += `安全帽位置：` + item.leftTopX + "," + item.leftTopY + " " + item.rightBottomX + "," + item.rightBottomY+ "\n";
        }
        result.value += `置信度：` + item.plateReliability*100 + "%\n\n";
      }

    } else {
      result.value = "检测失败，请重试";
    }
  }


const fetchImages = async () => {
  if (!selectedGroup.value) return;
  const response = await getPhotoOperationPict(selectedGroup.value);
  if (response.code === 0) {
    images.value = response.data || [];
    filteredImages.value = images.value;
    selectedImages.value = []; // 清空已选图片
    currentPage.value = 1; // 重置分页
  } else {
    console.error('获取图片失败');
  }
};

operationStore.$subscribe(async () => {
  operationId.value = operationStore.data[operationStore.index].id;
  await fetchdeviceData(); // 切换业务时刷新设备与图片数据
});
const applyDateFilter = () => {
  if (startDate.value || endDate.value) {
    filteredImages.value = images.value.filter((image) => {
      const imageDate = new Date(image.createTime);
      const start = startDate.value ? new Date(startDate.value) : null;
      const end = endDate.value ? new Date(endDate.value) : null;
      
      return (!start || imageDate >= start) && (!end || imageDate <= end);
    });
    currentPage.value = 1; 
  } else {
    filteredImages.value = images.value;
  }
};

const selectAll = () => {
  selectedImages.value = filteredImages.value.map((image) => image.id);
};

const deselectAll = () => {
  selectedImages.value = [];
};

const deleteSelected = async () => {
  const response = await deleteImages(selectedImages.value);
  if (response.success) {
    // Remove deleted images from the list
    images.value = images.value.filter(
      (image) => !selectedImages.value.includes(image.id)
    );
    filteredImages.value = images.value;
    selectedImages.value = [];
  }
};

const exportImages = () => {
  alert(`Exporting ${selectedImages.value.length} images`);
};

const paginatedImages = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage;
  return filteredImages.value.slice(start, start + itemsPerPage);
});

const totalPages = computed(() => Math.ceil(filteredImages.value.length / itemsPerPage));

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  }
};

const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

onMounted(() => {
  fetchdeviceData();
});

const showModal = ref(false);
const selectedImage = ref(null);

const openModal = (image) => {
  selectedImage.value = image;
  showModal.value = true;
};

const closeModal = () => {
  showModal.value = false;
  selectedImage.value = null;
};

const openUploadModal = () => {
  showUploadModal.value = true;
};

const closeUploadModal = () => {
  showUploadModal.value = false;
  uploadData.value = {
    selectedDevice: null,
    selectedTime: "",
    selectedImage: null,
  };
};
const handleFileUpload = (event) => {
  uploadData.value.selectedImage = event.target.files[0];
};


const uploadImage = async () => {
  if (!uploadData.value.selectedDevice || !uploadData.value.selectedTime || !uploadData.value.selectedImage) {
    alert("请完整填写所有信息！");
    return;
  }

  // 模拟上传请求
  const formData = new FormData();
  formData.append("device", uploadData.value.selectedDevice);
  formData.append("time", uploadData.value.selectedTime);
  formData.append("image", uploadData.value.selectedImage);

  try {
    const response = await yourUploadApiFunction(formData); // 替换为实际上传接口
    if (response.success) {
      alert("上传成功！");
      closeUploadModal();
      fetchImages(); // 刷新图片列表
    } else {
      alert("上传失败，请重试！");
    }
  } catch (error) {
    console.error(error);
    alert("上传失败，请重试！");
  }

  
};
</script>


<style scoped>
.container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-header {
  margin-left: 10px;
  width: 200px;
  border-left: 4px solid var(--primary-color);
}

.header-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
}

hr {
  margin-top: -10px;
  margin-bottom: 0px;
  box-align:center;
  width:99%;
  color:#e4e4e4;
  SIZE:1;
}

select {
  padding: 10px 10px;
  font-size: 18px;
  border: 0cqmax solid #ccc;
  border-radius: 5px;
  width: 100%;
}

.img-upload {
  margin: 5px;
  width: 100px;
  height: 40px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 17px;
}
.img-upload:hover {
  background-color: white;
  color: var(--primary-color);
  border: 1px solid var(--primary-color);
}


.date-filter {
  display: flex;
  align-items: center;
  gap: 20px;

  .inputselect {
    width: 200px;
    height: 30px;
    font-size: 17px;
  }
}

.date-filter input {
  padding: 5px;
  border-radius: 5px;
  border: 1px solid #ccc;
}

.date-filter button {
  padding: 5px 10px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.date-filter button:hover {
  background-color: white;
  color: var(--primary-color);
  border: 1px solid var(--primary-color);
}

.batch-actions {
  display: flex;
  gap: 10px;
}

.buttonselect {
  width: 100px;
  height: 40px;
  font-size: 17px;
}

.batch-actions button {
  padding: 5px 10px;
  background-color: white;
  color: var(--primary-color);
  border: 1px solid var(--primary-color);
  border-radius: 5px;
  cursor: pointer;

}

.batch-actions button:hover {
  background-color: var(--primary-color);
  color: white;
  }

.batch-actions button:disabled {
  background-color: #e0e0e0;
  cursor: not-allowed;
}

.image-grid-container {
  max-height: 100%;
  overflow-y: auto;
  border: none;
  border-radius: 10px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

.image-card {
  border: 1px solid #ddd;
  /* border-radius: 10px; */
  overflow: hidden;
  text-align: center;
  position: relative;
}

.image-card img {
  width: 100%;
  height: auto;
}

.image-info {
  height: 70px;
  background-color: #f9f9f9;
  font-size: 17px;
}

.image-checkbox {
  position: absolute;
  top: 10px;
  left: 10px;
  transform: scale(1.5); 
  z-index: 1;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
}

.pagination button {
  padding: 5px 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f5f5f5;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.pagination button:disabled {
  background-color: #e0e0e0;
  cursor: not-allowed;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  display: flex;
  background: #fff;
  border-radius: 10px;
  overflow: hidden;
  width: 80%;
  height: 80%;
  max-width: 80%;
  max-height: 80%;
  flex-direction: column;
  

  .modal-header {
    width: 100%;
    height: 7%;
    display: flex;
    justify-content: space-between; 
    padding: 10px;
    background-color: #f9f9f9;
    border-bottom: 1px solid #ddd;

    .image-time {
      margin-top: 10px;
      margin-left: 20px;
      font-size: 20px;
      color: var(--primary-color);
    }

    .close-button {
      background: none;
      border: none;
      margin-right: 30px;
      font-size: 40px;
      font-weight: bold;
      cursor: pointer;
      color: #333;
    }

    .close-button:hover {
      color: var(--primary-color);
    }

  }
  
  .model-content { 
    display: flex;
    width: 100%;
    height: 93%;
    flex-direction: row;
  }

  .image {
    margin-left: 20px;
    width: 70%; 
    height: 100%;
    object-fit: contain; 
  }

  .modal-sidebar {
    width: 30%;
    padding: 20px;
    display: flex;
    flex-wrap: wrap;
    flex-direction: column;
    gap: 10px;
    background-color: #f9f9f9;

    .modal-button {
        width: 200px;
        padding: 10px;
        background-color: var(--primary-color);
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: background-color 0.3s ease;
      }

      .modal-button:hover {
        background-color: var(--Nav-hover-color);
      }
  }

  
      
      
}
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
  z-index: 999; /* 确保在弹窗下面 */
}

.upload-modal {
  position: fixed;
  top: 0;
  right: 0;
  width: 45%;
  height: 100%;
  background: white;
  box-shadow: -2px 0 5px rgba(0, 0, 0, 0.2);
  z-index: 1000; /* 在遮罩层之上 */
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.upload-modal-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.title {
  height: 50px;
  text-align: center;
  margin-top: -10px;
}

.title h3 {
  color: var(--primary-color);
  font-size: 22px;
}

.form-item {
  display: flex;
  flex-direction: column;
}

.form-item label {
  font-weight: bold;
  margin-bottom: 5px;
}

.form-item select {
  border: 1px solid rgba(0, 0, 0, 0.5);
  width: 300px;
}

.form-item input {
  border-radius: 5px;
  font-size: 18px;
  border: 1px solid rgba(0, 0, 0, 0.5);
  width: 300px;
}

.form-actions {
  display: flex;
  justify-content:center;
  gap: 30px;
}

.buttonsave {
  padding: 10px;
  background-color: var(--primary-color);
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  width: 100px;
}

.buttoncancel {
  padding: 10px;
  background-color: #ccc;
  color: black;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  width: 100px;
}

.buttonsave:hover {
  background-color: var(--Nav-hover-color);
}



</style>
